package com.shelpe.services.sinbadgateway.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shelpe.services.sinbadgateway.client.SyncSchedulerClient;
import com.shelpe.services.sinbadgateway.client.SyncUserClient;
import com.shelpe.services.sinbadgateway.dto.PurchaseUserLoginDto;
import com.shelpe.services.sinbadgateway.dto.UserDto;
import com.shelpe.services.sinbadgateway.entity.jpa.AuthInfo;
import com.shelpe.services.sinbadgateway.entity.jpa.Users;
import com.shelpe.services.sinbadgateway.repository.jpa.AuthRepository;
import com.shelpe.services.sinbadgateway.repository.jpa.UsersRepository;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

	@Autowired
	private UsersRepository userRep;
	
	@Autowired
	private AuthRepository authRep;
	
	@Autowired
	private SyncSchedulerClient schedulerClient;
	
	@Autowired
	private SyncUserClient userClient;
	
	
	@Override
	public boolean purchaseUserLoginCheck(PurchaseUserLoginDto dto) {
		// TODO Auto-generated method stub
		Long userId = dto.getUserId();
		AuthInfo auth = authRep.findByTaobaoUserId(userId);
		if(auth == null){//可能是内部用户转订购
			auth = authRep.findByTaobaoUserNick(dto.getNick());
		}
		
		if(auth != null){//订购用户
			
			userId = auth.getTaobaoUserId();//以auth为准 
			Users user = userRep.findOne(userId);
			if(user != null){	
				if((userId < 0 && user.getUserType() == Users.USER_TYPE_PROXY)
						|| user.getInit() == 0){//原来的内部用户转订购用户
					
					dto.setUserId(userId);//返回真实的userId
					if(user.getInit() == 0){
						schedulerClient.syncUserJob(userId);
					}	
					userRep.updateUser(userId, 1, Users.USER_TYPE_PURCHASE);
				}
			}else{//users表中没有该用户
				UserDto userDto = userClient.createAndAddPurchaseUser(userId, auth.getTaobaoUserNick());
				if(userDto != null && userDto.getAddNum() != null && userDto.getAddNum() > 0){//新用户，同步其数据，同步数据的时候，会自动生成关键词及其报表的数据库表
					schedulerClient.syncUserJob(userId);
					
				}else{//创建用户失败
					
					log.error("purchaseUserLoginCheck: create new user failed, userId {}", userId);
					dto.setMessage("create new user failed");
					return false;
				}
			}
		}else{//非订购用户
			log.error("purchaseUserLoginCheck: has not purchased, userId {}", userId);
			dto.setMessage("has not purchased");
			return false;
		}
	
		return true;
	}

}
